﻿using Abp.vNext.WT.Application;
using Abp.vNext.WT.EntityFrameworkCore;
using Abp.vNext.WT.HttpApi;
using Microsoft.OpenApi.Models;
using System.Reflection;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Auditing;
using Volo.Abp.Autofac;
using Volo.Abp.Modularity;
using Volo.Abp.Swashbuckle;

namespace Abp.vNext.WT.WebApi
{
    // 模块类
    [DependsOn(
        typeof(HttpApiModule),
        typeof(ApplicationModule),
        typeof(AbpAutofacModule),
        typeof(EntityFrameworkCoreModule),
        typeof(AbpSwashbuckleModule)
        )]
    public class WebApiModule: AbpModule
    {
        // 是将你的服务添加到依赖注入系统并配置其他模块的主要方法
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            
            var configuration = context.Services.GetConfiguration();
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            // 配置swagger
            ConfigureSwaggerServices(context, configuration);

            Configure<AbpAuditingOptions>(options =>
            {
                options.IsEnabled = true;
                options.IsEnabledForGetRequests = true;
                options.IsEnabledForAnonymousUsers = true;
                options.ApplicationName = "Abp.vNext.WT.WebApi";
            });

            // 自动 将你的应用程序服务配置为API控制器
            Configure<AbpAspNetCoreMvcOptions>(options =>
            {
                //options.ConventionalControllers.Create(typeof(Abp.vNext.WT.Application.ApplicationModule).Assembly);
                options.ConventionalControllers.Create(typeof(ApplicationModule).Assembly, options =>
                {
                    // 配置根路径的显示名称
                    options.RootPath = "Abp.vNext.WT.WebApi";
                });
            });
            // 跨域
            ConfigureCors(context, configuration);
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors("cors");
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseSwagger();
            app.UseAbpSwaggerUI(options =>
            {
                options.DocumentTitle = $"{env.ApplicationName} - {env.EnvironmentName}";
                options.SwaggerEndpoint("/swagger/zwt/swagger.json", "App API");
                options.DisplayRequestDuration();

                //var configuration = context.GetConfiguration();
                //options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
                //options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
                //options.OAuthScopes("App");
            });

            app.UseAuditing();//使用审计日志
            app.UseUnitOfWork();
            app.UseConfiguredEndpoints();
        }

        #region Configure
        private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    options.AddPolicy("cors",
                    builder =>
                    {
                        builder.AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin();
                        builder.SetPreflightMaxAge(TimeSpan.FromMinutes(10));
                    });
                    //builder
                    //    .WithOrigins(
                    //        configuration["App:CorsOrigins"]
                    //            .Split(",", StringSplitOptions.RemoveEmptyEntries)
                    //            .Select(o => o.RemovePostFix("/"))
                    //            .ToArray()
                    //    )
                    //    .WithAbpExposedHeaders()
                    //    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    //    .AllowAnyHeader()
                    //    .AllowAnyMethod()
                    //    .AllowCredentials();
                });
            });
        }

        private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("zwt", new OpenApiInfo
                {
                    Version = "1.0.0.9",
                    Title = "abp_vNext服务数据管理接口",
                    Description = "",
                    Contact = new OpenApiContact { Name = "zhangwentao", Email = "1459289161@qq.com" },
                    License = new OpenApiLicense { Name = "ThreeGuys" },
                });

                c.DescribeAllParametersInCamelCase(); 
                c.DocInclusionPredicate((docName, description) => true);//这个很重要，没有的话swagger只显示当前项目里的api contraller
                c.CustomSchemaIds(type => type.FullName);

                // 为 Swagger JSON and UI设置xml文档注释路径
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录（绝对，不受工作目录影响，建议采用此方法获取路径）
                var name=Assembly.GetExecutingAssembly().GetName().Name+ ".xml";
                var xmlPath = Path.Combine(basePath, name);
                c.IncludeXmlComments(xmlPath, true);
            });
            #region 权限
            //context.Services.AddAbpSwaggerGenWithOAuth(
            //configuration["AuthServer:Authority"],
            //new Dictionary<string, string>
            //{
            //        {"App", "App API"}
            //},
            //options =>
            //{
            //    options.SwaggerDoc("v1", new OpenApiInfo { Title = "App API", Version = "v1" });
            //    options.DocInclusionPredicate((docName, description) => true);
            //    options.CustomSchemaIds(type => type.FullName);
            //});
            #endregion
        }
        #endregion
    }
}
